package com.foreknow.controller;

import com.foreknow.bean.Guest;
import com.foreknow.service.GuestService;
import com.foreknow.service.impl.GuestServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class AddMessageServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置从服务器端向客户端返回的内容的类型   MIME类型：text/html
        resp.setContentType("text/html;charset=utf-8");
        //客户端向服务器端请求的编码格式(否则会产生乱码)  默认：iOS 8859-1
        req.setCharacterEncoding("UTF-8");
        //获取打印流用于向网页输出内容
        PrintWriter out = resp.getWriter();
        //获取请求参数
        String name = req.getParameter("name");
        String phone = req.getParameter("phone");
        String email = req.getParameter("email");
        String title = req.getParameter("title");
        String content = req.getParameter("content");
        //将时间转换为字符串形式
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        String dateString = df.format(date);
        Guest guest = new Guest();
        guest.setName(name);
        guest.setPhone(phone);
        guest.setEmail(email);
        guest.setTitle(title);
        guest.setContent(content);
        guest.setCreatedtime(dateString);
        GuestService service = new GuestServiceImpl();
        boolean isRight = service.register(guest);
        if (isRight){
            //请求转发
            //req.getRequestDispatcher("Select").forward(req,resp);
            //重定向
            resp.sendRedirect("Select");
        }else {
            out.println("error...");
        }
    }
}
